package com.wurd.flink;

import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class ServerSocketDemo {

    public static void main(String[] args) {
        new ServerSocketDemo().createSocket();
    }

    public void createSocket() {
        new Thread(() -> {
            try {
                ServerSocket server = new ServerSocket();
                server.bind(new InetSocketAddress(3333));
                while (true) {
                    Socket socket = null;
                    try {
                        socket = server.accept();
                        OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream());
                        Random random = new Random();
                        while (true) {
                            writer.write(random.nextInt(100) + "\n");
                            writer.flush();
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (socket != null) {
                            socket.close();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}
